package com.gzy.demo1.config;

import com.gzy.demo1.model.Account;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jws;
import io.jsonwebtoken.Jwt;
import io.jsonwebtoken.Jwts;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.web.authentication.www.BasicAuthenticationFilter;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Enumeration;


public class JWTAuthenticationFilter extends BasicAuthenticationFilter {


    JWTUserDetailsService userDetailsService;

    public JWTAuthenticationFilter(AuthenticationManager authenticationManager,JWTUserDetailsService userDetailsService) {
        super(authenticationManager);
        this.userDetailsService = userDetailsService;
    }

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws IOException, ServletException {
        // 访问接口前
        String token = request.getHeader("Token");
        if (StringUtils.isEmpty(token)){
            chain.doFilter(request, response);
            return;
        }

        Jws<Claims> claimsJws = Jwts.parser()
                .setSigningKey("123456789")
                .parseClaimsJws(token);
        Claims body = claimsJws.getBody();
        String username = body.getSubject();

//        Account
        User userDetails = (User) userDetailsService.loadUserByUsername(username);

//   principal 主体   credentials 凭证    authorities 权限
//        Object principal, Object credentials, Collection<? extends GrantedAuthority > authorities
        UsernamePasswordAuthenticationToken authentication =  new UsernamePasswordAuthenticationToken(userDetails, null, userDetails.getAuthorities());

        SecurityContextHolder.getContext().setAuthentication(authentication);

        chain.doFilter(request, response);


        // 接口处理完毕之后
    }
}
